package com.coocaa.internship.interceptor;

import com.coocaa.internship.common.ResultData;
import com.coocaa.internship.dao.UserLoginDao;
import com.coocaa.internship.pojo.UserLogin;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description:
 * @Author: 凌贤
 * @Date: 2019-08-09
 * @Time: 16:06
 */
public class UserRoleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserLoginDao userLoginDao = getClass(UserLoginDao.class, request);
        String userId = null;
        for (Cookie cookie :
                request.getCookies()) {
            if (cookie.getName().equals("userId")) {
                userId = cookie.getValue();
            }
        }
        UserLogin userLogin = userLoginDao.selectUserLoginById(Long.valueOf(userId));
        if (userLogin.getUserRole().equals("admin")) {
            return true;
        } else {
            sendError(response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private <T> T getClass(Class<T> tClass, HttpServletRequest request) {
        WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return applicationContext.getBean(tClass);
    }

    private void sendError(HttpServletResponse response) {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        if (response.getStatus() != 200) {
        } else {
            try {
                out = response.getWriter();
                out.append(ResultData.builder().code(10).message("没有权限").build().toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
